package cn.john.hrm.exception;

import cn.john.hrm.util.AjaxResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

@RestControllerAdvice
public class HrmExceptionHandler {

    /**
     * 处理算数运行异常
     * @param e
     * @return
     */
    @ExceptionHandler(ArithmeticException.class)
    public AjaxResult arithmeticExceptionHandle(ArithmeticException e) {
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }

    /**
     * 对所有异常进行处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandle(Exception e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }


    /**
     * 处理jsr303校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException e) {
        List<FieldError> errors = e.getBindingResult().getFieldErrors();
        HashMap<Object, Object> map = new HashMap<>();
        errors.stream().forEach(fieldError -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return AjaxResult.me().setSuccess(false).setMessage(map.toString());
    }

}
